package com.google.androidcamp.session4.provider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;

import com.google.androidcamp.session4.data.DBAdapter;

public class NotesProvider extends ContentProvider {
    public static final Uri CONTENT_URI = Uri.parse("content://com.google.androidcamp/note");
    public static final String KEY_NOTETEXT = DBAdapter.KEY_NOTETEXT;
    
    private static final int ALL_NOTES_CODE = 0;
    // Matched used to validate supported URI formats.
    private static final UriMatcher uriMatcher;
    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI("com.google.androidcamp", "note", ALL_NOTES_CODE);
        // uriMatcher.addURI("com.google.androidcamp", "note/#", 1);
    }
    
    private DBAdapter mDbAdapter;
    
    @Override
    public boolean onCreate() {
        mDbAdapter = new DBAdapter(getContext());
        mDbAdapter.open();
        return true;
    }
    
    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
        // Only 1 URI format is supported at this time.  If multiple formats
        // were supported, add them here.
        case ALL_NOTES_CODE:
            return "vnd.android.cursor.dir/vnd.google.androidcamp.note";
        //case NOTE_CODE:
        //    return "vnd.android.cursor.item/vnd.google.androidcamp.note";
        default:
            throw new IllegalArgumentException("Unsupported URI: " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        if (uriMatcher.match(uri) == ALL_NOTES_CODE) {
            mDbAdapter.saveNote(values);
            getContext().getContentResolver().notifyChange(uri, null);
            return uri;
        }
        return null;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        if (uriMatcher.match(uri) == ALL_NOTES_CODE) {
            return mDbAdapter.getNote();
        }
        return null;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        if (uriMatcher.match(uri) == ALL_NOTES_CODE) {
            return (int) mDbAdapter.saveNote(values);
        }
        return 0;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        // Not supported.  Do nothing.
        return 0;
    }

    @Override
    public void shutdown() {
        super.shutdown();
        if (mDbAdapter != null) {
            mDbAdapter.close();
        }
    }
}
